package org.hy.common.utils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author hy
 * @version 1.0
 * @date 2020-09-21 16:02
 */
public final class ListUtils {

    private ListUtils(){
        throw new AssertionError("no instance for you.");
    }

    public static String join(Collection<String> collection, String separator){
        Objects.requireNonNull(separator, "separator must not be null.");
        if(isNotEmpty(collection)){
            StringBuffer sb = new StringBuffer();
            collection.forEach(s -> sb.append(s).append(separator));
            sb.delete(sb.lastIndexOf(separator), sb.length());
            return sb.toString();
        }
        return StringUtils.EMPTY;
    }

    public static String join(Collection<String> collection){
        return join(collection, ",");
    }

    public static <T> boolean isNotEmpty(Collection<T> collection){
        return collection != null && !collection.isEmpty();
    }

    public static <T> boolean isNotEmpty(T[] ts){
        return ts != null && ts.length > 0;
    }

    public static <T, TO> List<TO> convert(List<T> list, Function<T, TO> function){
        if(isNotEmpty(list)){
            return list.stream().map(function).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public static <T, K> Map<K, T> toMap(List<T> list, Function<T, K> f){
        Map<K, T> map = new HashMap<>();
        if(isNotEmpty(list)){
            list.forEach(t -> map.put(f.apply(t), t));
        }
        return map;
    }

    public static <T> List<T> of(T...ts){
        final List<T> list = new ArrayList<>();
        if(isNotEmpty(ts)){
            for (T t: ts) {
                if(t != null){
                    list.add(t);
                }
            }
        }
        return list;
    }
}
